package com.baihejia.common.dubbo.server;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.ServiceConfig;
import com.baihejia.common.dubbo.server.cache.Cache;
import com.baihejia.common.dubbo.service.Api;
import com.baihejia.common.dubbo.server.ApiImpl;

import java.util.ArrayList;
import java.util.List;

//服务端启动
public class Server {

	static {
		Logger.init();
		Cache.init();
		Configuration.init();

		/*ClientParameter parameter = new ClientParameter();
		parameter.connectionTimeout = 30000;
		parameter.namespace = "com.baihejia.thrift.house";
		parameter.sessionTimeout = 30000;
		parameter.singleton = true;
		parameter.zkHosts = Configuration.get("zkHosts");
		parameter.maxActive = 5;
		parameter.idleTime = 180000;
		parameter.services = Arrays.asList(LocationService.class);
		parameter.version = "1.0.0";

		HouseThrift.init(parameter);*/
	}

	public static void main(String[] args) {
		System.setProperty("java.net.preferIPv4Stack", "true");
		
		//TODO  端口号
		int dubboQosPort = 33338;
//		int dubboQosPort = 33333;
        System.setProperty("dubbo.qos.port", String.valueOf(dubboQosPort));

		// 当前应用配置
		ApplicationConfig application = new ApplicationConfig();
		application.setName(String.format("%s-%s", Server.class.getName(), dubboQosPort));
		application.setOwner(Server.class.getName());

		// 连接注册中心配置
		List<RegistryConfig> registryConfigList = new ArrayList<>();
		String[] zkHosts = Configuration.get("zkHosts").split(",|;");
		for (String zkHost : zkHosts) {
			RegistryConfig registry = new RegistryConfig();
			registry.setAddress(String.format("zookeeper://%s", zkHost));
			registry.setTimeout(30000);
			registryConfigList.add(registry);
		}

		// 服务提供者协议配置
		ProtocolConfig protocol = new ProtocolConfig();
		protocol.setName("dubbo");
		protocol.setPort(-1);
		protocol.setThreads(200);

		// 注意：ServiceConfig为重对象，内部封装了与注册中心的连接，以及开启服务端口

		// 服务提供者暴露服务配置
		ServiceConfig<Api> service = new ServiceConfig<Api>(); // 此实例很重，封装了与注册中心的连接，请自行缓存，否则可能造成内存和连接泄漏
		service.setApplication(application);
		service.setRegistries(registryConfigList); // 多个注册中心可以用setRegistries()
		service.setProtocol(protocol); // 多个协议可以用setProtocols()
		service.setInterface(Api.class);
		service.setRef(new ApiImpl());
		service.setVersion("1.0.0");

		// 暴露及注册服务
		service.export();
		try {
			synchronized (Server.class) {
				Server.class.wait();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
